<template>
    <el-dialog
        v-model="dialogVisible"
        title="编辑任务信息"
        width="30%"
        :before-close="handClose"
    >
        <div>
            <el-form :model="formData" ref="formRef" label-width="80px" :rules="rules">
                <el-form-item label="任务名称" prop="taskName">
                    <el-input 
                        v-model="formData.taskName" 
                        placeholder="请输入任务名称"
                        :prefix-icon="EditPen"
                    />
                </el-form-item>
                <el-form-item label="任务分组" prop="groupID">
                    <el-select v-model="formData.groupID" class="m-2" placeholder="请选择分组">
                        <el-option
                            v-for="item in groups"
                            :key="item.groupID"
                            :label="item.groupName"
                            :value="item.groupID"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="标签" prop="tagIDs">
                    <el-tag
                        v-for="tag in formData.tagIDs"
                        :key="tag"
                        class="mx-1 selectedTag"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)"
                    >
                        {{ getTagName(tag) }}
                    </el-tag>
                    <el-select 
                        v-if="inputVisible"
                        ref="InputRef"
                        v-model="inputValue" 
                        class="m-2" 
                        placeholder="Select"
                        @change="handleInputConfirm"
                    >
                        <el-option
                            v-for="item in tagIdOptios"
                            :key="item.tagID"
                            :label="item.tagName"
                            :value="item.tagID"
                        />
                    </el-select>
                    <el-button v-else class="" size="small"  @click="showInput">
                        + 新建标签
                    </el-button>
                </el-form-item>
                <el-form-item label="备注" prop="mark">
                    <el-input 
                        v-model="formData.mark" 
                        placeholder="备注信息"
                        type="textarea"
                        :prefix-icon="Notebook"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="mOrder">
                    <el-input 
                        v-model="formData.mOrder" 
                        placeholder="请输入排序, 数值越大越靠前"
                        :prefix-icon="Sort"
                    />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="confirmDialog(formRef)">
            确认
            </el-button>
        </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed, defineProps, defineEmits, watch, nextTick} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox, ElInput} from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
import { Sort, EditPen,Notebook } from '@element-plus/icons-vue'
import RPAApi from '../../../apis/rpa'
import {useUserStore} from '../../../stores/user'
import { FormValid } from '../../../utils/FormUtils'

const router = useRouter();
const route = useRoute();
const userStore = useUserStore()

const groups = ref<Array<{groupID:string,groupName:string}>>([])
const inputValue = ref('')
const tagIdOptios = ref<Array<{tagID:string, tagName:string}>>([]);
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const props = defineProps({
    isShow: Boolean,
    handleUpdated: Function,
    data: Object
})

const formRef = ref<FormInstance>()
const formData = ref({
    id: "",
    taskName:"",
    groupID: "",
    mOrder: 0,
    mark:"",
    tagIDs:[]
});

const rules = reactive<FormRules>({
    taskName: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 3, max: 32, message: '最小长度3, 最大长度16', trigger: 'blur' },
    ],
    groupID: [
        { required: true, message: '请选择分组', trigger: 'change' },
    ],
    mOrder: [
        { required: true, message: '请输入排序, 数字', trigger: 'blur' },
    ]
})

const emit = defineEmits(['update:isShow']);

const dialogVisible = ref(props.isShow);
watch(()=> props.isShow,() => {
    console.log('props.isShow change', props.isShow);
    dialogVisible.value = props.isShow
});
watch(()=> props.data,() => {
    console.log('props.data change', props.data);
    formData.value.id = props.data?.id;
    formData.value.taskName = props.data?.taskName;
    formData.value.groupID = props.data?.groupID;
    formData.value.mOrder = props.data?.morder;
    formData.value.mark = props.data?.mark;
    formData.value.tagIDs = props.data?.tagIDs.split(',');
},{
    immediate:true
});


onMounted(()=>{
    console.log("[EditRPATaskDialog]onMounted");
    loadData();
})

const loadData = ()=>{
    // 获取分组信息
    RPAApi.fetchRPAGroup("", 0, 999).then(ret=>{
        if(ret.code == 0){
            groups.value = ret.data.list;
        }
    }).catch(err=>{
        console.log("[CreateRPATaskDialog]fetchRPAGroup err", err);
    })

    RPAApi.fetchRPATag("", 0, 999).then(ret=>{
        if(ret.code == 0){
            tagIdOptios.value = ret.data.list;
        }
    }).catch(err=>{
        console.log("[CreateRPATaskDialog]fetchRPAGroup err", err);
    });
}

const getTagName = (tagId:string) =>{
    let filter = tagIdOptios.value.filter(item=>item.tagID == tagId);
    if(filter && filter.length>0){
        return filter[0].tagName;
    }
}

const handClose = () =>{
    console.log('handClose');
    emit('update:isShow', false)
}

const closeDialog = () => {
    console.log('closeDialog');
    emit('update:isShow', false)
}

const confirmDialog = (formRef: FormInstance | undefined) => {
    if (!formRef) return;
    FormValid(formRef).then(ret=>{
        return RPAApi.updateTask(formData.value.id, formData.value.taskName, formData.value.groupID, formData.value.tagIDs, formData.value.mark);
    }).then(ret=>{
        if(ret.code == 0){
            ElMessage({
                type: 'success',
                message: "更新成功",
            });
            if(props.handleUpdated){
                props.handleUpdated();
            }
            setTimeout(async () => {
                emit('update:isShow', false)
            }, 1500);
        }else{
            ElMessage({
                type: 'error',
                message: "更新失败",
            });
        }
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err
        });
    });
    
}

const handleClose = (tag: string) => {
  formData.value.tagIDs.splice(formData.value.tagIDs.indexOf(tag as never), 1)
}

const showInput = () => {
  inputVisible.value = true
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.value.tagIDs.push(inputValue.value as never)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style scoped>
.selectedTag {
    margin-top: 3px;
    margin-right: 5px;
    margin-bottom: 3px;
}
</style>
